<?php
namespace Models;
use Phalcon\Mvc\Model;
class ModelBase extends Model
{
    protected $prefix='w_';
    protected static $server;
    public function initialize() {
        $this->prefix=$this->getDI()->get('config')->database['prefix'];
        self::setup(array(
            'notNullValidations' => false
        ));
    
    }
    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        $tables=  explode('\\', get_class($this));
        $table=  array_pop($tables);
        return $this->prefix . strtolower(preg_replace('/(?<=[a-z])(?=[A-Z])/', '_',$table ));
    }

    public function beforeUpdate(){
        $mod=$this->toArray();
        $pk=self::getPk($this);
        if(!empty($pk)){
            $pkval=$mod[$pk];
        }else{
            list($pk,$pkval)=each($mod);
        }
        $m=self::findFirst([$pk.'=?1','bind'=>[1=>$pkval]]);
        if($m !==false){
            $name=$this->getSource();
            $name=ltrim($name,$this->prefix);
            $before=$m->toArray();
            \Library\Common::setTable($name.'_'.$pkval,json_encode($before));
        }

    }

    public function afterUpdate(){
        $name=$this->getSource();
        $name=ltrim($name,$this->prefix);
        $ser=self::getServer();
        $controller=$this->getDI()->get('dispatcher')->getControllerName();
        $action=$this->getDI()->get('dispatcher')->getActionName();
        $ser->task(['type'=>'modelEvent','action'=>$controller.'/'.$action,'model'=>$name,'data'=>serialize($this),'event'=>'afterUpdate']);
    }

    public static function getPK($model=''){

        $metaData = new \Phalcon\Mvc\Model\MetaData\Memory();
        $attributes = $metaData->getPrimaryKeyAttributes($model);

        return $attributes[0];
    }


    public  static function getServer(){
        if(!static::$server){
            self::$server=\Server\Server::getServer();
        }
        return self::$server;
    }

}

?>